package com.gaofans.nrpc.common.protocol;

import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author GaoFans
 */
public abstract class Message implements Serializable {

    public final static byte RPC_REQUEST = 0;
    public final static byte RPC_RESPONSE = 1;
    public final static byte PING = 2;
    public final static byte PONG = 3;
    private static final Map<Byte,Class<? extends Message>> MESSAGE_CLASSES = new ConcurrentHashMap<>();

    static {
        MESSAGE_CLASSES.put(RPC_REQUEST,RpcRequest.class);
        MESSAGE_CLASSES.put(RPC_RESPONSE,RpcResponse.class);
        MESSAGE_CLASSES.put(PING,PingMessage.class);
        MESSAGE_CLASSES.put(PONG,PongMessage.class);
    }

    public static void register(byte type,Class<? extends Message> messageClass){
        MESSAGE_CLASSES.put(type,messageClass);
    }

    public static Class<? extends Message> getMessageClass(byte type){
        return MESSAGE_CLASSES.get(type);
    }

    /**
     * 消息的唯一id
     */
    private long sequenceId;

    private HashMap<String, Serializable> headers;
    public long getSequenceId() {
        return sequenceId;
    }

    public void setSequenceId(long sequenceId) {
        this.sequenceId = sequenceId;
    }

    public void putHeader(String key,Serializable value){
        if (headers == null){
            headers = new HashMap<>(8);
        }
        headers.put(key,value);
    }
    public Serializable header(String key){
        if (headers == null){
            return null;
        }
        return headers.get(key);
    }
    public Serializable removeHeader(String key){
        return headers.remove(key);
    }
    /**
     * 获取数据类型
     * @return
     */
    public abstract byte getType();

    /**
     * 获取消息头map
     * @return
     */
    public Map<String,Serializable> headers(){
        if (headers == null){
            return null;
        }
        return Collections.unmodifiableMap(headers);
    };

}
